<?php
module_load_include('inc', 'lastbuyer', 'lastbuyer');
module_load_include('inc', 'crf', 'crf');
module_load_include('inc', 'lastbuyer', 'lastbuyer.api');
function lastbuyer_buynow_form(&$form_state,$nid){
  $form = array();
  modalframe_child_js();
  $form['nid']=  array('#type' => 'hidden', '#value' => $nid);
  $form['key']=  array('#type' => 'hidden', '#value' => user_password(20));

  //display table of product sumary.
  $node = node_load($nid);
  $header =  array(t('Product name'),t('Image'),t('Price'),t('Quality'));
  $rows = array();
  $rows[]=array(l($node->title, 'node/'. $node->nid),
  theme('image',$node->last_buyer['image'],$node->title,$node->title,array('width'=>'300px'),FALSE),
  lb_number_format($node->last_buyer['price'],0).$node->last_buyer['currency'],1);
  $table =  theme('table', $header, $rows);
  $form['info'] = array( '#value' => $table);
  $form['payment_method'] = array(
   '#type' => 'select', 
   '#title' => t('Payment method'), 
   '#default_value' => variable_get('PAYMENT_METHOD_DEFAULT',PAYMENT_METHOD_DEFAULT),
   '#options' => array(
  PAYMENT_METHOD_DEFAULT => t('Baokim'),
  ),
   '#suffix' => '<div>'.l(t("Click here if you don't have BaoKim Account"),BAOKIM_REF_LINK,array('attributes'=> array('target' => '_blank'))).'</div>', 
  );
  $form['submit'] = array('#type' => 'submit', '#value' => t('Confirm'),'#attributes' => array('class' => 'css3Button'),);
  return $form;
}


function lastbuyer_buynow_form_submit($form, &$form_state) {
  $nid =$form_state['values']['nid'];
  global $user;
  //insert lastbuyer_transaction: status =0
  $point = 0;
  $index =0;
  $sql =  "SELECT COUNT(*) FROM {lastbuyer_transaction} WHERE uid=%d AND nid=%d AND in_day=1 AND point >0";
  $point = db_result(db_query($sql,$user->uid,$nid,$end_date))>0 ? 0 : 1;
  $sql = "INSERT INTO {lastbuyer_transaction} (uid, status, nid, point,idx,in_day,buy_date,method,trace_id) VALUES (%d, %d, %d, %d, %d,%d,%d,%d,NULL)";
  db_query($sql,$user->uid , 0, $nid, $point, $index, 1,time(),$form_state['values']['payment_method']);

  //update lastbuyer_product: number_of_buy_in_day=number_of_buy_in_day+1
  $sql = "UPDATE {lastbuyer_product} SET number_of_buy_in_day=number_of_buy_in_day+1 WHERE nid=%d";
  db_query($sql,$nid);
  $node = node_load($nid);
  drupal_goto("https://www.baokim.vn/giao-dich/chuyen-tien-baokim");
}
function updateall_traceid(){
  global  $user;
  $header = array(t('user id'),t('product id'),t('status'),t('in day'),t('buy date'),t('point'),t('index'),t('trace id'));
  $sql  = "SELECT t.tid,t.nid,n.title,t.buy_date,t.trace_id FROM {lastbuyer_transaction} AS t "
  ." JOIN  {node} AS n ON n.nid=t.nid WHERE t.uid=%d AND t.in_day =1";
  $header = array(t('product'),t('buy date'),t('trace id'),t('Operations'));
  $query = pager_query($sql,10,get_pager_index('updateall_traceid'),NULL,$user->uid);
  while ($r = db_fetch_array($query)) {
    $data =  array();
    $data[] = l($r['title'],'node/'.$r['nid']);
    $data[] = date('D, d M Y H:i:s',$r['buy_date']);
    $data[] = $r['trace_id'];
    $data[] = l(t('update trace id'),'last_buyer/update/tradeid/'.$r['tid']);
    $row[] =  $data;
  }
  return theme('table',$header,$row).theme('pager', array('«','‹','|','›','»'), 10,get_pager_index('updateall_traceid'),array() ,3);
}
function update_traceid_form(&$form_state,$tid){
  $sql  = "SELECT t.tid,t.nid,n.title,t.buy_date,t.trace_id FROM {lastbuyer_transaction} AS t "
  ." JOIN  {node} AS n ON n.nid=t.nid WHERE t.tid=%d AND t.in_day =1";
  $query = db_query($sql,$tid);
  $header = array(t('product'),t('buy date'),t('trace id'));
  while ($r = db_fetch_array($query)) {
    $data =  array();
    $data[] = l($r['title'],'node/'.$r['nid']);
    $data[] = date('D, d M Y H:i:s',$r['buy_date']);
    $data[] = $r['trace_id'];
    $row[] =  $data;
  }

  $form['product'] =array('#value' => theme('table',$header,$row));
  $form['trace_id'] =array(
      '#type' => 'textfield', 
      '#title' => t('Trace id'),
  );
  $form['tid']=  array('#type' => 'hidden', '#value' => $tid);
  $form['submit'] = array('#type' => 'submit', '#value' => t('Update'));
  return $form;
}
function update_traceid_form_submit($form, &$form_state) {
  $tid =$form_state['values']['tid'];
  $trace_id =$form_state['values']['trace_id'];
  global  $user;
  $success =  true;
  //cap nhat thoi guan chay batch khong cho cap nhat sao trade
  if(lb_is_running_batch()) {
    drupal_set_message(t("You can't update traceid. System is running a batch!"),'warning');
  }else{
    if (user_access('administer site configuration')) {
      $sql = "UPDATE {lastbuyer_transaction} SET trace_id='%s' WHERE tid=%d";
      db_query($sql,$trace_id,$tid);
      if(@db_query($sql,$trace_id,$tid,$user->uid)==FALSE){
        if(db_error()==1062 ){
          drupal_set_message(t("You trace id is updated. Can't update one trace id for 2 or more transaction"),'error');
        }else{
          drupal_set_message(t('Update trace is fail!'),'error');
        }
        $success =  FALSE;
      }
    }else{
      $sql = "UPDATE {lastbuyer_transaction} SET trace_id='%s' WHERE tid=%d AND uid=%d";
      if(@db_query($sql,$trace_id,$tid,$user->uid)==FALSE){
        if(db_error()==1062 ){
          drupal_set_message(t("You trace id is updated. Can't update one trace id for 2 or more transaction"),'error');
        }else{
          drupal_set_message(t('Update trace is fail!'),'error');
        }
        $success =  FALSE;
      }
    }
    if($success){
      drupal_set_message(t('Update trace id successful!'));
    }
  }
}
function  get_donated_money_block_content(){
  $sql = 'SELECT SUM(number_of_buy) FROM {lastbuyer_product} WHERE status > 0';

  return lb_number_format((db_result(db_query($sql)) * lb_get_default_price() /2)+ variable_get('donated_by_partner',0),2).'VND';
}
function get_sponsor_block_content(){
  $primary_sponsor =variable_get('sponsor_block_primary_sponsor',0);
  $result = '<div style="width:'.variable_get('sponsor_block_width',210).'px">';
  $pageSize = 0;
  if($primary_sponsor){
    $sql = 'SELECT * FROM {sponsor} WHERE sid=%d';
    $sponsor = db_fetch_array(db_query($sql,$primary_sponsor));
    $result .= '<div styple="width'.variable_get('sponsor_block_width',210).'">';
    $result.= '<a href="'.$sponsor['link'].'"><img style="padding:0px 5px 0px 0px" src="'.$sponsor['image'].'" width="'.((variable_get('sponsor_block_width',210))-5).'"/></a>';
    $result .='</div>';
    $sql = 'SELECT * FROM {sponsor} WHERE sid <> %d ORDER BY weight ASC';
    $pageSize =variable_get('default_sponsor_block_size_b',2);
    $query = pager_query($sql,$pageSize,get_pager_index('sponsor_block_pager'),NULL,$primary_sponsor);
  }else{
    $pageSize = variable_get('default_sponsor_block_size',4);
    $sql = 'SELECT * FROM {sponsor} ORDER BY weight ASC';
    $query = pager_query($sql,$pageSize,get_pager_index('sponsor_block_pager'),NULL);
  }
  $left ='<div style="float: left;width:'.(variable_get('sponsor_block_width',210)/2).'">';
  while (($sponsor = db_fetch_array($query)) !== FALSE) {
    $left.= '<a href="'.$sponsor['link'].'"><img style="padding:0px 5px 0px 0px" src="'.$sponsor['image'].'" width="'.((variable_get('sponsor_block_width',210)/2)-5).'"/></a>';
  }
  $left .= '</div>';
  $result .= $left;
  $result .='</div>';
  $result .='<div class="sponsor">'.theme('pager', array('«','‹','|','›','»'), $pageSize,get_pager_index('sponsor_block_pager'),array(),3).'</div>';
  return $result;
}

function get_list_all_transaction($nid){
  $sql =  "SELECT t.tid,t.uid,t.status,t.nid,t.point,t.idx,t.in_day,t.buy_date,t.trace_id,n.title,u.name,t.ref_date FROM {lastbuyer_transaction} AS t "
  ." JOIN {users} AS u ON t.uid = u.uid JOIN {node} AS n ON n.nid=t.nid WHERE t.nid=%d ORDER  BY t.buy_date DESC";
  $pageSize =  variable_get('list_transaction_all_size',10);
  $query = pager_query($sql,$pageSize,get_pager_index('list_transaction_all'),NULL,$nid);
  global $pager_page_array;
  $pager_current = $pager_page_array[get_pager_index('list_transaction_all')];
  if(!$pager_current){
    $pager_current= 0;
  }
  $statuses = _get_status_array();
  $i =$pager_current*$pageSize;
  while ($r = db_fetch_array($query)) {
    $data =  array();
    $i++;
    $data[] = $i;
    $data[] = l($r['name'],'user/'.$r['uid']);
    $data[] = l($r['title'],'node/'.$r['nid']);
    $data[] = format_date($r['buy_date'],'custom','d-m-Y H:i:s');
    $data[] = $statuses[$r['status']];
    $data[] = format_date($r['ref_date'],'custom','d-m-Y H:i:s');
    $data[] = $r['trace_id'];
    $rows[] = $data;
  }
  
  $header = array(t('No.'),t('user'),t('product'),t('buy date'),t('status'),t('Reference date'),t('trace id'));
  return theme('table', $header, $rows);
}

function user_view_transactions($uid){
  $sql =  "SELECT t.tid,t.uid,t.status,t.nid,t.point,t.idx,t.in_day,t.buy_date,t.trace_id,n.title,u.name,t.ref_date FROM {lastbuyer_transaction} AS t "
  ." JOIN {users} AS u ON t.uid = u.uid JOIN {node} AS n ON n.nid=t.nid WHERE t.uid=%d ORDER  BY t.nid DESC, t.buy_date DESC";
  $pageSize =  variable_get('list_transaction_all_size',10);
  $query = pager_query($sql,$pageSize,get_pager_index('user_view_transactions'),NULL,$uid);
  $statuses = _get_status_array();
  global $pager_page_array;
  $pager_current = $pager_page_array[get_pager_index('user_view_transactions')];
  if(!$pager_current){
    $pager_current= 0;
  }
  $i =$pager_current*$pageSize;
  while ($r = db_fetch_array($query)) {
    $data =  array();
    $i++;
    $data[] = $i;
    $data[] = l($r['name'],'user/'.$r['uid']);
    $data[] = l($r['title'],'node/'.$r['nid']);
    $data[] = format_date($r['buy_date'],'custom','d-m-Y H:i:s');
    $data[] = $statuses[$r['status']];
    $data[] = format_date($r['ref_date'],'custom','d-m-Y H:i:s');
    $data[] = $r['trace_id'];
    $rows[] = $data;
  }
  $header = array(t('No.'),t('user'),t('product'),t('buy date'),t('status'),t('Reference date'),t('trace id'));
  return theme('table', $header, $rows).theme('pager', array('«','‹','|','›','»'), 10,get_pager_index('user_view_transactions'),array() ,3);
}
function _get_description_for_bonus($type,$description,$other){
  $desc = unserialize($description);
  $options =  $desc[1];
  $options['!nid'] = l($other[0]['title'],'node/'.$other[0]['nid']);
  return  t($desc[0],$options);
  
}
function user_view_points($uid){
  $sql =  "SELECT t.tid,t.uid,t.status,t.nid,p.point,t.idx,t.in_day,t.buy_date,t.trace_id,n.title,t.ref_date,p.description,p.type,p.create_date FROM {lastbuyer_transaction} AS t"
  ." JOIN {node} AS n ON n.nid=t.nid LEFT JOIN {bonus_point} AS p ON p.ref_id=t.tid WHERE t.uid=%d AND p.status=%d ORDER  BY t.nid DESC, t.buy_date DESC";
  $pageSize =  variable_get('list_transaction_all_size',10);
  $query = pager_query($sql,$pageSize,get_pager_index('user_view_points'),NULL,$uid,1);
  $statuses = _get_status_array();
  global $pager_page_array;
  $pager_current = $pager_page_array[get_pager_index('user_view_points')];
  if(!$pager_current){
    $pager_current= 0;
  }
  $i =$pager_current*$pageSize;
  while ($r = db_fetch_array($query)) {
    $data =  array();
    $i++;
    $data[] = $i;
    $data[] = format_date($r['create_date'],'custom','d-m-Y H:i:s');
    $data[] = $r['point'];
    $data[] = _get_description_for_bonus($r['type'],$r['description'],array($r));
    $rows[] = $data;
  }
  $header = array(t('No.'),t('Date'),t('Point'),t('description'));
  return theme('table', $header, $rows).theme('pager', array('«','‹','|','›','»'), 10,get_pager_index('user_view_points'),array() ,3);
}
function compare_lb_record($a,$b){
  $x = $a[0] - $a[3];
  $y = $b[0] - $b[3];
  return $x == $y? 0 : ($x < $y ? -1: 1);
}
function view_top_win($nid){
  $sql =  "SELECT * FROM {lastbuyer_records} WHERE nid = %d ORDER BY rid DESC";
  $query =db_query_range($sql,$nid, 0, 10);
  $first = FALSE;
  $i = 0;
  $statuses = _get_status_array();
  while (($r = db_fetch_array($query)) !== FALSE) {
    if($first == FALSE){
      $first = $r['section'];
    }
    if($first == $r['section']){
      $i++;
      $data =  array();
      $data[] = $i;
      $data[] = l($r['name'],'user/'.$r['uid']);
      $data[] = l($r['title'],'node/'.$r['nid']);
      $data[] = format_date($r['buy_date'],'custom','d-m-Y H:i:s');
      $data[] = $statuses[$r['status']];
      $data[] = format_date($r['ref_date'],'custom','d-m-Y H:i:s');
      $data[] = $r['trace_id'];
      $result[] = $data;
    }
  }
  if(isset($result) && !empty($result)){
    //Need to show
	uasort($result, 'compare_lb_record');
  }
  $header = array(t('No.'),t('user'),t('product'),t('buy date'),t('status'),t('Reference date'),t('trace id'));
  print(theme('table', $header, $result));
  module_invoke_all('exit');
  exit(0);
}
function ajax_view_done_transactions($nid){
  $sql =  "SELECT t.tid,t.uid,t.status,t.nid,t.point,t.idx,t.in_day,t.buy_date,t.trace_id,n.title,u.name,t.ref_date FROM {lastbuyer_transaction} AS t "
  ." JOIN {users} AS u ON t.uid = u.uid JOIN {node} AS n ON n.nid=t.nid WHERE t.in_day=0 AND t.nid=%d ORDER  BY t.nid DESC, t.buy_date DESC";
  $pageSize =  variable_get('list_transaction_all_size',10);
  $query = pager_query($sql,$pageSize,get_pager_index('view_done_transactions'),NULL,$nid);
  $statuses = _get_status_array();
  global $pager_page_array;
  $pager_current = $pager_page_array[get_pager_index('view_done_transactions')];
  if(!$pager_current){
    $pager_current= 0;
  }
  $i =$pager_current*$pageSize;
  while ($r = db_fetch_array($query)) {
    $data =  array();
    $i++;
    $data[] = $i;
    $data[] = l($r['name'],'user/'.$r['uid']);
    $data[] = l($r['title'],'node/'.$r['nid']);
    $data[] = format_date($r['buy_date'],'custom','d-m-Y H:i:s');
    $data[] = $statuses[$r['status']];
    $data[] = format_date($r['ref_date'],'custom','d-m-Y H:i:s');
    $data[] = $r['trace_id'];
    $rows[] = $data;
  }
  $header = array(t('No.'),t('user'),t('product'),t('buy date'),t('status'),t('Reference date'),t('trace id'));
  $table =  theme('table', $header, $rows);
  if($_GET['more-link']=='f'){
    $pre = '';
    $page_options = array('#options'=>TRUE,'options'=>array('attributes'=>array('class'=>'ajax-link','rel'=>'#ajax_ldt_'.$nid)));
  }else{
    $page_options = array('more-link'=>'f','#options'=>TRUE,'options'=>array('attributes'=>array('class'=>'ajax-link','rel'=>'#ajax_ldt_'.$nid)));
    $pre ='<span>'.l(t('reload'),'last_buyer/ajax/view/done/transactions/'.$nid,array('query'=>array('more-link'=>'f'),'attributes'=>array('class'=>'ajax-link refresh-link','rel'=>'#ajax_ldt_'.$nid))).'</span>';
  }
  $result=
  $pre
  .'<div id="ajax_ldt_'.$nid.'">'.$table
  .theme('pager', array('«','‹','|','›','»'), 10,get_pager_index('view_done_transactions'),$page_options ,3);

  $result.= '</div><script type="text/javascript">
<!--//--><![CDATA[//><!--
Drupal.attachBehaviors($(ajax_ldt_'.$nid.').get(0));
//--><!]]>
</script>';
  print($result);
  module_invoke_all('exit');
  exit(0);

}

function ajax_view_transactions($nid){

  if($_GET['more-link']=='f'){
    $pre = '';
    $page_options = array('#options'=>TRUE,'options'=>array('attributes'=>array('class'=>'ajax-link','rel'=>'#ajax_lvt_'.$nid)));
  }else{
    $page_options = array('more-link'=>'f','#options'=>TRUE,'options'=>array('attributes'=>array('class'=>'ajax-link','rel'=>'#ajax_lvt_'.$nid)));
    $pre ='<span>'.l(t('reload'),'last_buyer/ajax/view/transactions/'.$nid,array('query'=>array('more-link'=>'f'),'attributes'=>array('class'=>'ajax-link refresh-link','rel'=>'#ajax_lvt_'.$nid))).'</span>';
  }
  print(
  $pre
  .'<div id="ajax_lvt_'.$nid.'">'.get_list_all_transaction($nid)
  .theme('pager', array('«','‹','|','›','»'), 10,get_pager_index('list_transaction_all'),$page_options ,3));
  print('</div><script type="text/javascript">
<!--//--><![CDATA[//><!--
Drupal.attachBehaviors($(ajax_lvt_'.$nid.').get(0));
//--><!]]>
</script>');
  module_invoke_all('exit');
  exit(0);
}
?>
